package com.quanyan.place.service.impl;

import com.quanyan.api.APIResponse;
import com.quanyan.common.utils.DateTimeUtils;
import com.quanyan.common.utils.DateUtils;
import com.quanyan.place.biz.IBaseService;
import com.quanyan.place.biz.ISearchService;
import com.quanyan.place.client.PlaceClient;
import com.quanyan.place.constants.PlaceConstants;
import com.quanyan.place.entity.*;
import com.quanyan.place.entity.vo.BuyPlaceUnitInfo;
import com.quanyan.place.entity.vo.PlaceUnitBaseInfo;
import com.quanyan.place.entity.vo.PlaceUnitTime;
import com.quanyan.place.mapper.*;
import com.quanyan.place.request.IsBuyPlaceUnitRequest;
import com.quanyan.place.response.IsBuyPlaceUnitResponse;
import com.quanyan.place.service.CacheService;
import com.quanyan.place.service.ContractService;
import com.quanyan.place.service.PlaceBuyService;
import com.quanyan.place.service.PlaceInnerService;
//import com.quanyan.place.thread.PlaceBuyContractThread;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import static com.quanyan.place.constants.PlaceConstants.PLACE_CONTRACT_VERIFY_NO;
import static com.quanyan.place.constants.PlaceConstants.PLACE_CONTRACT_VERIFY_YES;
//import java.util.concurrent.ExecutorService;
//import java.util.concurrent.Executors;

/**
 * 场馆购买合同信息处理
 * Created by zhang on 16/4/16.
 */
@Service("placeBuyService")
public class PlaceBuyServiceImpl implements PlaceBuyService {
    private final static Logger logger = LoggerFactory.getLogger(PlaceBuyServiceImpl.class);

    @Autowired
    private TbBizPlaceBuyContractMapper placeBuyContractMapper;

    @Autowired
    private TbBizPlaceBuyContractDetailMapper placeBuyContractDetailMapper;

    @Autowired
    private PlaceInnerService placeClient;

    @Autowired
    private TbBizPlaceMapper placeMapper;

    @Autowired
    private TbBizPlaceAttachMapper placeAttachMapper;

    @Autowired
    private CacheService cacheService;

    @Autowired
    private ContractService contractService;
//    @Autowired
//    private TbBizPlaceBuyContractStatisticsMapper placeBuyContractStatisticsMapper;

    @Autowired
    private TbBizPlaceUnitMapper placeUnitMapper;

//    @Autowired
//    private TbBizPlaceUnitStatisticsMapper placeUnitStatisticsMapper;
//
//    @Autowired
//    private TbBizPlaceUnitPrimeTimeMapper placeUnitPrimeTimeMapper;

    @Autowired
    private TbBizPlaceUnitTimeMapper placeUnitTimeMapper;


    @Autowired
    ISearchService searchService;
    ExecutorService cachedThreadPool = Executors.newSingleThreadExecutor();
//    ExecutorService cachedThreadPool = Executors.newCachedThreadPool();

    private static final int interval = 60;

//    @Autowired
//    private ISearchService searchService;

    /**
     * 添加场馆购买合同信息
     *
     * @param placeBuyContract
     * @return
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED,rollbackFor = Exception.class)
    public APIResponse<?> addPlaceBuyContract(PlaceBuyContract placeBuyContract) {

        TbAdminUser user;
        try {
            user = cacheService.getAdminUser(placeBuyContract.getUid());
        } catch ( Exception e) {
            e.printStackTrace();
            return APIResponse.returnFail("该用户未登录，请重新登录");
        }
        /*
        //判断购买年限是否超过上限
        if(this.isBuyOvertopMax(placeBuyContract)){
            return APIResponse.returnFail("场地购买年限请勿超过五年");
        }
        */
        if (null != user) {
            int flag = 0;

            TbBizPlace tbBizPlace = null;
            // 如果合同号为空需要按照规则生成：
            // 合同编号，改为系统生成，规则是：以场馆编号打头，加两位自增流水号。如：BJZH019763是场馆编号，合同编号是BJZH01976301新增加的内容
            if (StringUtils.isEmpty(placeBuyContract.getContractNo())) {
                tbBizPlace = this.placeMapper.selectByPrimaryKey(placeBuyContract.getPlaceId());
                String code = tbBizPlace.getCode();
                if (StringUtils.isEmpty(code)) {
                    return APIResponse.returnFail("该场馆没有编码，无法自动生成合同号");
                }

                // TODO: 16-10-18 需要一个生成2位流水号的服务！
                long suffix = cacheService.getRunningNumber("placeBuyContract_", placeBuyContract.getPlaceId().toString());
                String newContractNo = String.format("%s%02d", code, suffix);
                placeBuyContract.setContractNo(newContractNo);
            }

            TbBizPlaceBuyContract voVal = contractService.getContractInfoByContractNo(placeBuyContract.getContractNo());
            if (voVal != null) {
                return APIResponse.returnFail("该合同编号已经在使用！");
            }

            //添加购买场馆合同信息
            TbBizPlaceBuyContract tbBizPlaceBuyContract = this.savePlaceBuyContractInfo(placeBuyContract,user);

            if (tbBizPlaceBuyContract.getId() >= 1) {
                //添加购买场地详细信息
                flag = savePlaceBuyContractDetail(placeBuyContract,user,tbBizPlaceBuyContract);
                if (flag > 0) {
                    //更新签约状态为已签约（1）
                    flag = 0;
                    flag = this.updatePlaceSign(placeBuyContract.getPlaceId());
                    if (flag > 0) {
                        //添加场馆购进合同统计信息
//                        cachedThreadPool.execute(new PlaceBuyContractThread(
//                                placeBuyContract,
//                                tbBizPlaceBuyContract.getId(),
//                                placeBuyContractStatisticsMapper,
//                                placeAttachMapper,
//                                placeUnitStatisticsMapper,
//                                placeUnitPrimeTimeMapper,
//                                placeUnitTimeMapper));

                        try{
                            //调用solr增加索引
                            if (tbBizPlace == null) {
                                tbBizPlace = this.placeMapper.selectByPrimaryKey(placeBuyContract.getPlaceId());
                            }
                            final TbBizPlace tbBizPlaceTmp = tbBizPlace;
                            cachedThreadPool.execute(new Runnable() {
                                @Override
                                public void run() {
                                    searchService.addPlaceIndex(tbBizPlaceTmp, null);
                                }
                            });
                        }catch (Exception e){
                            logger.error("调用solr增加索引异常 placeId：{},eror:{}",placeBuyContract.getPlaceId(), e);
                        }

                        placeBuyContract.setId(tbBizPlaceBuyContract.getId());
                        return APIResponse.returnSuccess();
                    } else {
                        return APIResponse.returnFail("场馆状态修改失败");
                    }

                } else {
                    return APIResponse.returnFail("场馆场地购买合同信息添加失败");
                }

            } else {
                return APIResponse.returnFail("场馆购买合同信息添加失败");
            }
        } else {
            return APIResponse.returnFail("该用户不存在");
        }
    }
    /**
     * 通过场馆Id获取购买的场馆场地信息
     * @param placeId
     * @return
     */
    @Override
    public APIResponse<?> getPlaceBuyContractInfoByPlaceId(Integer placeId) {

        List<BuyPlaceUnitInfo> buyPlaceUnitInfoList = new ArrayList<>();
        //获取场馆信息
        APIResponse<TbBizPlace> placeResult = placeClient.getPlaceData(placeId);
        if(placeResult.isRet()){
            TbBizPlace tbBizPlace = placeResult.getData();
            BuyPlaceUnitInfo buyPlaceUnitInfo;
            //获取场馆合同信息
            List<TbBizPlaceBuyContract> placeBuyContractList = this.getPlaceBuyContractByPlaceId(placeId);
            if(!placeBuyContractList.isEmpty()){
                //获取场馆场地列表信息
                Map<Integer,TbBizPlaceUnit> map = new HashMap<>();
                APIResponse<List<TbBizPlaceUnit>> placeUnitResult = placeClient.getPlaceUnitData(placeId,-1);
                if(placeUnitResult.isRet()){

                    List<TbBizPlaceUnit> tbBizPlaceUnitList = placeUnitResult.getData();
                    if (!tbBizPlaceUnitList.isEmpty()) {
                        for (TbBizPlaceUnit placeUnit : tbBizPlaceUnitList) {
                            //map中存放的是以场地ID作为key值的相对应的场地信息
                            map.put(placeUnit.getId(),placeUnit);
                        }
                    }
                }
                //循环场馆里面的每一个合同信息
                for (TbBizPlaceBuyContract tbBizPlaceBuyContract : placeBuyContractList) {

                    buyPlaceUnitInfo = new BuyPlaceUnitInfo();
                    buyPlaceUnitInfo.setPlaceName(tbBizPlace.getName());
                    buyPlaceUnitInfo.setPlaceId(placeId);
                    buyPlaceUnitInfo.setBillingCycle(tbBizPlaceBuyContract.getBillingCycle());
                    buyPlaceUnitInfo.setBuyDate(tbBizPlaceBuyContract.getBuyDate());
                    buyPlaceUnitInfo.setTotalPrice(tbBizPlaceBuyContract.getTotalPrice());
                    buyPlaceUnitInfo.setBuyType(tbBizPlaceBuyContract.getBuyType());
                    buyPlaceUnitInfo.setSignDate(tbBizPlaceBuyContract.getSignDate());
                    buyPlaceUnitInfo.setRemark(tbBizPlaceBuyContract.getRemark());
                    buyPlaceUnitInfo.setCreateDate(tbBizPlaceBuyContract.getCreateTime());
                    buyPlaceUnitInfo.setContractNo(tbBizPlaceBuyContract.getContractNo());

                    //查询合同下的每个场地信息
                    List<TbBizPlaceBuyContractDetail> list = this.getPlaceBuyContractDetailListByContractId(tbBizPlaceBuyContract.getId());
                    PlaceUnitBaseInfo placeUnitBaseInfo;
                    if (!list.isEmpty()) {
                        List<PlaceUnitBaseInfo> placeUnitBaseInfoList = new ArrayList<>();
                        Set<Integer> set = new HashSet<>();
                        for (TbBizPlaceBuyContractDetail tbBizPlaceBuyContractDetail : list) {
                            set.add(tbBizPlaceBuyContractDetail.getPlaceUnitId());
                        }
                        for (Integer i : set) {

                            TbBizPlaceUnit tbBizPlaceUnit = map.get(i);
                            if (tbBizPlaceUnit != null) {
                                placeUnitBaseInfo = new PlaceUnitBaseInfo();
                                placeUnitBaseInfo.setPlaceUnitId(tbBizPlaceUnit.getId());
                                placeUnitBaseInfo.setPlaceUnitName(tbBizPlaceUnit.getName());
                                placeUnitBaseInfo.setFieldScale(tbBizPlaceUnit.getFieldScale());
                                placeUnitBaseInfo.setLightType(tbBizPlaceUnit.getLightType());
                                placeUnitBaseInfo.setPlaceUnitTexture(tbBizPlaceUnit.getPlaceUnitTexture());
                                placeUnitBaseInfo.setPlaceUnitType(tbBizPlaceUnit.getPlaceUnitType());
                                List<PlaceBuyContractDetail> placeBuyContractDetailList = this.getPlaceBuyContractDetailByPlaceUnitId(tbBizPlaceUnit.getId(),tbBizPlaceBuyContract.getId());
                                placeUnitBaseInfo.setPlaceBuyContractDetailList(placeBuyContractDetailList);
                                placeUnitBaseInfoList.add(placeUnitBaseInfo);
                            }
                        }
                        buyPlaceUnitInfo.setPlaceUnitBaseInfoList(placeUnitBaseInfoList);
                    }
                    buyPlaceUnitInfoList.add(buyPlaceUnitInfo);
                }
            }
        } else {
            return APIResponse.returnFail("该场馆不存在");
        }


        return APIResponse.returnSuccess(buyPlaceUnitInfoList);
    }
    /**
     * 判断场地是否买入
     * @param is
     * @return
     */
    @Override
    public IsBuyPlaceUnitResponse isBuyPlaceUnit(IsBuyPlaceUnitRequest is) {

        IsBuyPlaceUnitResponse response = new IsBuyPlaceUnitResponse();

        //查询该场馆是否购买
        List<TbBizPlaceBuyContract> placeBuyContractList = this.getPlaceBuyContractByPlaceId(is.getPlaceId());
        if (!placeBuyContractList.isEmpty()) {  //场馆合同存在
            //int buyType = placeBuyContractList.get(0).getBuyType();
            List<TbBizPlaceBuyContractDetail> tbBizPlaceBuyContractDetailList = this.getPlaceBuyContractDetail(is.getPlaceUnitId());
            if(!tbBizPlaceBuyContractDetailList.isEmpty()){ //查询的场馆场地合同信息存在
                //判断是否购买了该日期的该时段
               /* int week = DateUtils.getDayOfWeek(is.getSaleDate());
                if(buyType == 1 && buyType == 2) {
                    TbBizPlaceAttach placeAttach = this.getPlaceAttachInfo(is.getPlaceId());
                    if (placeAttach != null) {
                        String hour_start = "";
                        String hour_end = "";
                        if(week == 6 && week == 7){
                            hour_start = placeAttach.getHolidayBusinessHourStart();
                            hour_end = placeAttach.getHolidayBusinessHourEnd();
                        }else{
                            hour_start = placeAttach.getBusinessHourStart();
                            hour_end = placeAttach.getBusinessHourStart();
                        }


                    }
                }*/
               /* if (buyType == 3){
                    for (TbBizPlaceBuyContractDetail tbBizPlaceBuyContractDetail : tbBizPlaceBuyContractDetailList) {

                    }
                }*/

            }else{
                response.setIsBuy(false);
                return response;
            }

        }else{  //场馆合同不存在
            response.setIsBuy(false);
            return response;
        }
        response.setIsBuy(false);
        return response;
    }

    /**
     * 通过场馆ID获取场地营业时间列表
     * @param placeUnitId
     * @return
     */
    @Override

    public APIResponse<?> getPlaceUnitTimeList(Integer placeUnitId) {
        List<PlaceUnitTime> placeUnitTimeList = new ArrayList<>();
        List<TbBizPlaceUnitTime> placeUnitPrimeTimeList = this.getPlaceUnitPrimeTimeList(placeUnitId);
        if (!placeUnitPrimeTimeList.isEmpty()) {
            for (TbBizPlaceUnitTime placeUnitTime : placeUnitPrimeTimeList) {
                String start = placeUnitTime.getStartTime();
                String end = placeUnitTime.getEndTime();
                List<String> timeList = DateTimeUtils.getIntervalTimeList(start,end,PlaceBuyServiceImpl.interval);
                if (!timeList.isEmpty()) {
                    PlaceUnitTime unitTime;
                    int size = timeList.size() - 1 ;
                    for (int n = 0; n < size; n++){
                        unitTime = new PlaceUnitTime();
                        unitTime.setStartTime(timeList.get(n));
                        unitTime.setEndTime(timeList.get(n + 1));
                        unitTime.setPlaceUnitId(placeUnitId);
                        unitTime.setTimeType(placeUnitTime.getTimeType());
                        //0为非黄金时段，1为黄金时段
                        unitTime.setIsPrimeTime(placeUnitTime.getIsPrimeTime());
                        placeUnitTimeList.add(unitTime);
                    }
                }
            }
        }

        return APIResponse.returnSuccess(placeUnitTimeList);
    }

    /**
     * 判断要删除的场馆或者场地是否可以删除
     * @param type :判断场馆是否可以删除type为1，判断场馆内的场地是否可以删除type为2
     * @param param :如果type==1，则param为场馆ID;如果type==2，则param为场馆场地ID
     * @return 可删除则返回true，否则返回false
     */
    @Override
    public boolean isDeletePlace(Integer param, Integer type) {

        if(type.equals(1)){ //场馆是否可删除
            List<TbBizPlaceBuyContract> list = this.getPlaceBuyContractByPlaceId(param);
            if (list.isEmpty()) {
                return true;
            } else {
                for (TbBizPlaceBuyContract tbBizPlaceBuyContract : list) {
                    //通过合同ID获取相关的合同详情
                    List<TbBizPlaceBuyContractDetail> placeBuyContractDetailList = this.getPlaceBuyContractDetailListByContractId(tbBizPlaceBuyContract.getId());
                    if (placeBuyContractDetailList.isEmpty()) {
                        continue;
                    } else {
                        for (TbBizPlaceBuyContractDetail tbBizPlaceBuyContractDetail : placeBuyContractDetailList) {
                            if(DateUtils.compare(new Date(), tbBizPlaceBuyContractDetail.getFinishDate(), false)){
                                continue;
                            } else {
                                return false;
                            }
                        }
                    }
                }
            }
        }else if(type.equals(2)){   //场馆场地是否可删除
            List<TbBizPlaceBuyContractDetail> placeBuyContractDetailList = this.getPlaceBuyContractDetail(param);
            if (placeBuyContractDetailList.isEmpty()) {
                return true;
            } else {
                for (TbBizPlaceBuyContractDetail tbBizPlaceBuyContractDetail : placeBuyContractDetailList) {
                    if(DateUtils.compare(new Date(),tbBizPlaceBuyContractDetail.getFinishDate(),false)){
                        continue;
                    } else {
                        return false;
                    }
                }
            }
        }
        return true;
    }


    /**
     * 通过场馆Id获取场馆场地列表
     * @param placeId
     * @return
     */
    @Override
    public APIResponse<?> getBuyPlaceInfoById(Integer placeId) {
        BuyPlaceUnitInfo buyPlaceUnitInfo = new BuyPlaceUnitInfo();

        //获取场馆信息
        APIResponse<TbBizPlace> placeResult = placeClient.getPlaceData(placeId);
        if(placeResult.isRet()){

            TbBizPlace tbBizPlace = placeResult.getData();
            if(tbBizPlace != null){
                buyPlaceUnitInfo.setPlaceName(tbBizPlace.getName());
                buyPlaceUnitInfo.setPlaceId(tbBizPlace.getId());
                buyPlaceUnitInfo.setCode(tbBizPlace.getCode());
            }else{
                return APIResponse.returnFail("该场馆不存在！！！");
            }
        } else {
            return APIResponse.returnFail("该场馆不存在！！！");
        }

        //获取场馆场地列表信息
        APIResponse<List<TbBizPlaceUnit>> placeUnitResult = placeClient.getPlaceUnitData(placeId,-1);
        if(placeUnitResult.isRet()){
            List<PlaceUnitBaseInfo> placeUnitBaseInfoList = new ArrayList<>();
            PlaceUnitBaseInfo placeUnitBaseInfo;
            List<TbBizPlaceUnit> tbBizPlaceUnitList = placeUnitResult.getData();
            if(!tbBizPlaceUnitList.isEmpty()){
                for (TbBizPlaceUnit tbBizPlaceUnit : tbBizPlaceUnitList) {
                    //判断场地是否签约和删除
                    if(tbBizPlaceUnit.getIsSign().byteValue() == 0){
                        placeUnitBaseInfo = new PlaceUnitBaseInfo();
                        placeUnitBaseInfo.setPlaceUnitId(tbBizPlaceUnit.getId());
                        placeUnitBaseInfo.setPlaceUnitName(tbBizPlaceUnit.getName());
                        placeUnitBaseInfo.setFieldScale(tbBizPlaceUnit.getFieldScale());
                        placeUnitBaseInfo.setLightType(tbBizPlaceUnit.getLightType());
                        placeUnitBaseInfo.setPlaceUnitTexture(tbBizPlaceUnit.getPlaceUnitTexture());
                        placeUnitBaseInfo.setPlaceUnitType(tbBizPlaceUnit.getPlaceUnitType());
                        placeUnitBaseInfo.setIsSign(0);
                        placeUnitBaseInfoList.add(placeUnitBaseInfo);
                    } else if(tbBizPlaceUnit.getIsSign().byteValue() == 1){
                        List<TbBizPlaceBuyContractDetail> placeBuyContractDetailList = this.getPlaceBuyContractDetail(tbBizPlaceUnit.getId());
                        if(placeBuyContractDetailList.isEmpty()){
                            placeUnitBaseInfo = new PlaceUnitBaseInfo();
                            placeUnitBaseInfo.setPlaceUnitId(tbBizPlaceUnit.getId());
                            placeUnitBaseInfo.setPlaceUnitName(tbBizPlaceUnit.getName());
                            placeUnitBaseInfo.setFieldScale(tbBizPlaceUnit.getFieldScale());
                            placeUnitBaseInfo.setLightType(tbBizPlaceUnit.getLightType());
                            placeUnitBaseInfo.setPlaceUnitTexture(tbBizPlaceUnit.getPlaceUnitTexture());
                            placeUnitBaseInfo.setPlaceUnitType(tbBizPlaceUnit.getPlaceUnitType());
                            placeUnitBaseInfo.setIsSign(0);
                            placeUnitBaseInfoList.add(placeUnitBaseInfo);
                        }else{
                            int flag = 0;
                            for (TbBizPlaceBuyContractDetail tbBizPlaceBuyContractDetail : placeBuyContractDetailList) {
                            if (tbBizPlaceBuyContractDetail.getFinishDate()!=null) {
                                if (DateUtils.dateCompare(DateUtils.getToday(), tbBizPlaceBuyContractDetail.getFinishDate(), true)) {
                                    //将已过期的合同详情的过期状态进行修改
                                    this.updatePlaceBuyContractDetailExpire(tbBizPlaceBuyContractDetail.getId());
                                } else {
                                    //未过期的合同总数
                                    flag++;
                                }
                            }
                            }
                            //表明无未过期合同，可以进行重新购进
                            if(flag == 0){
                                placeUnitBaseInfo = new PlaceUnitBaseInfo();
                                placeUnitBaseInfo.setPlaceUnitId(tbBizPlaceUnit.getId());
                                placeUnitBaseInfo.setPlaceUnitName(tbBizPlaceUnit.getName());
                                placeUnitBaseInfo.setFieldScale(tbBizPlaceUnit.getFieldScale());
                                placeUnitBaseInfo.setLightType(tbBizPlaceUnit.getLightType());
                                placeUnitBaseInfo.setPlaceUnitTexture(tbBizPlaceUnit.getPlaceUnitTexture());
                                placeUnitBaseInfo.setPlaceUnitType(tbBizPlaceUnit.getPlaceUnitType());
                                placeUnitBaseInfo.setIsSign(0);
                                placeUnitBaseInfoList.add(placeUnitBaseInfo);
                            }
                        }

                    }

                }
                buyPlaceUnitInfo.setPlaceUnitBaseInfoList(placeUnitBaseInfoList);
            }else{
                //如果场馆场地为空时，返回一个size=0 的 List
                buyPlaceUnitInfo.setPlaceUnitBaseInfoList(placeUnitBaseInfoList);
                return APIResponse.returnSuccess(buyPlaceUnitInfo);
            }

        } else {
            return APIResponse.returnFail("该场馆场地信息有误");
        }

        return APIResponse.returnSuccess(buyPlaceUnitInfo);
    }

    /**
     * 添加购买场馆合同信息
     * @param placeBuyContract
     * @return
     */
    public TbBizPlaceBuyContract savePlaceBuyContractInfo(PlaceBuyContract placeBuyContract, TbAdminUser adminUser){
        TbBizPlaceBuyContract tbBizPlaceBuyContract = new TbBizPlaceBuyContract();
        //插入付款周期，时段买入无付款周期信息
        if(placeBuyContract.getBuyType().equals(3)){
            tbBizPlaceBuyContract.setBillingCycle(0);
        }else{
            tbBizPlaceBuyContract.setBillingCycle(placeBuyContract.getBillingCycle());
        }
        //根据合同生效时间，合同失效时间，判断合同的状态
        if(DateUtils.dateTimeCompare(placeBuyContract.getBuyDate(), new Date(), false)){
            placeBuyContract.setStatus(PlaceConstants.PLACE_CONTRACT_UNEXECUTED);
        }else{
            placeBuyContract.setStatus(PlaceConstants.PLACE_CONTRACT_EXECUTED);
            if (DateUtils.dateTimeCompare(new Date(),placeBuyContract.getFinishDate(),false)){
                placeBuyContract.setStatus(PlaceConstants.PLACE_CONTRACT_END);
            }
        }
        tbBizPlaceBuyContract.setBuyDate(placeBuyContract.getBuyDate());
        tbBizPlaceBuyContract.setBuyType(placeBuyContract.getBuyType());
        tbBizPlaceBuyContract.setPlaceId(placeBuyContract.getPlaceId());
        tbBizPlaceBuyContract.setTotalPrice(placeBuyContract.getTotalPrice());
        tbBizPlaceBuyContract.setCreateTime(new Date());
        tbBizPlaceBuyContract.setUpdateTime(new Date());
        tbBizPlaceBuyContract.setUid(adminUser.getId());
        tbBizPlaceBuyContract.setDeptId(adminUser.getDeptId());
        tbBizPlaceBuyContract.setSignDate(placeBuyContract.getSignDate());
        tbBizPlaceBuyContract.setPhone(placeBuyContract.getPhone());
        tbBizPlaceBuyContract.setRemark(placeBuyContract.getRemark());
        tbBizPlaceBuyContract.setSignPeople(placeBuyContract.getSignPeople());
        tbBizPlaceBuyContract.setContractNo(placeBuyContract.getContractNo());
        tbBizPlaceBuyContract.setStatus(placeBuyContract.getStatus());

        // 增加新的写入字段
        tbBizPlaceBuyContract.setReceiveCompanyName(placeBuyContract.getReceiveCompanyName());
        tbBizPlaceBuyContract.setTaxRate(placeBuyContract.getTaxRate());
        tbBizPlaceBuyContract.setInvoice(placeBuyContract.getInvoice());
        tbBizPlaceBuyContract.setAccountWay(placeBuyContract.getAccountWay());
        tbBizPlaceBuyContract.setCalRentStartTime(placeBuyContract.getCalRentStartTime());
        tbBizPlaceBuyContract.setCalRentEndTime(placeBuyContract.getCalRentEndTime());

        tbBizPlaceBuyContract.setIsVerify(PLACE_CONTRACT_VERIFY_YES);

        placeBuyContractMapper.insertSelective(tbBizPlaceBuyContract);
        return tbBizPlaceBuyContract;
    }

    /**
     * 添加购买场地的详细信息
     * @param placeBuyContract
     * @return
     */
    public int savePlaceBuyContractDetail(PlaceBuyContract placeBuyContract, TbAdminUser adminUser, TbBizPlaceBuyContract tbBizPlaceBuyContract){
        List<PlaceBuyContractDetail> placeBuyContractDetailList = placeBuyContract.getPlaceBuyContractDetails();

        int flag = 0;
        TbBizPlaceBuyContractDetail tbBizPlaceBuyContractDetail;
        if(placeBuyContract.getBuyType().equals(PlaceConstants.BUY_TYPE_GROUP)){

            for (PlaceBuyContractDetail placeBuyContractDetail : placeBuyContractDetailList) {
                tbBizPlaceBuyContractDetail = new TbBizPlaceBuyContractDetail();
                tbBizPlaceBuyContractDetail.setBuyDate(placeBuyContract.getBuyDate());
                tbBizPlaceBuyContractDetail.setPlaceId(placeBuyContractDetail.getPlaceId());
                tbBizPlaceBuyContractDetail.setPlaceUnitPrice(placeBuyContractDetail.getPlaceUnitPrice());
                tbBizPlaceBuyContractDetail.setPlaceUnitExpires(placeBuyContractDetail.getPlaceUnitExpires());
                tbBizPlaceBuyContractDetail.setExpiresUnit("年");
                tbBizPlaceBuyContractDetail.setAttractId(tbBizPlaceBuyContract.getId());
                tbBizPlaceBuyContractDetail.setBuyType(placeBuyContract.getBuyType());
                tbBizPlaceBuyContractDetail.setPlaceUnitId(placeBuyContractDetail.getPlaceUnitId());
                tbBizPlaceBuyContractDetail.setUid(adminUser.getId());
                tbBizPlaceBuyContractDetail.setDeptId(adminUser.getDeptId());
                tbBizPlaceBuyContractDetail.setFinishDate(DateUtils.addTime(placeBuyContract.getBuyDate(),(int)(placeBuyContractDetail.getPlaceUnitExpires()*12),0));
                placeBuyContractDetailMapper.insertSelective(tbBizPlaceBuyContractDetail);
                flag ++ ;
                this.updatePlaceUnitSign(placeBuyContractDetail.getPlaceUnitId());
            }
        }
        if(placeBuyContract.getBuyType().equals(PlaceConstants.BUY_TYPE_WHOLE)){
            for (PlaceBuyContractDetail placeBuyContractDetail : placeBuyContractDetailList) {
                tbBizPlaceBuyContractDetail = new TbBizPlaceBuyContractDetail();
                tbBizPlaceBuyContractDetail.setBuyDate(placeBuyContract.getBuyDate());
                tbBizPlaceBuyContractDetail.setPlaceId(placeBuyContractDetail.getPlaceId());
                tbBizPlaceBuyContractDetail.setPlaceUnitPrice(placeBuyContractDetail.getPlaceUnitPrice());
                tbBizPlaceBuyContractDetail.setPlaceUnitExpires(placeBuyContractDetail.getPlaceUnitExpires());
                tbBizPlaceBuyContractDetail.setExpiresUnit("年");
                tbBizPlaceBuyContractDetail.setAttractId(tbBizPlaceBuyContract.getId());
                tbBizPlaceBuyContractDetail.setBuyType(placeBuyContract.getBuyType());
                tbBizPlaceBuyContractDetail.setPlaceUnitId(placeBuyContractDetail.getPlaceUnitId());
                //tbBizPlaceBuyContractDetail.setFinishDate(DateUtils.addTime(placeBuyContract.getBuyDate(),(int)(placeBuyContract.getPlaceExpires()*12),0));
                tbBizPlaceBuyContractDetail.setFinishDate(placeBuyContract.getFinishDate());
                tbBizPlaceBuyContractDetail.setUid(adminUser.getId());
                tbBizPlaceBuyContractDetail.setDeptId(adminUser.getDeptId());
                placeBuyContractDetailMapper.insertSelective(tbBizPlaceBuyContractDetail);
                flag ++ ;
                this.updatePlaceUnitSign(placeBuyContractDetail.getPlaceUnitId());
            }
        }
        if(placeBuyContract.getBuyType().equals(PlaceConstants.BUY_TYPE_TIME) ||
                placeBuyContract.getBuyType().equals(PlaceConstants.BUY_TYPE_TRUE_TIME) ||
                placeBuyContract.getBuyType().equals(PlaceConstants.BUY_TYPE_FALSE_TIME)){
            for (PlaceBuyContractDetail placeBuyContractDetail : placeBuyContractDetailList) {
                tbBizPlaceBuyContractDetail = new TbBizPlaceBuyContractDetail();
                tbBizPlaceBuyContractDetail.setBuyDate(placeBuyContract.getBuyDate());
                tbBizPlaceBuyContractDetail.setFinishDate(placeBuyContractDetail.getFinishDate());
                tbBizPlaceBuyContractDetail.setPlaceId(placeBuyContractDetail.getPlaceId());
                tbBizPlaceBuyContractDetail.setPlaceUnitPrice(placeBuyContractDetail.getPlaceUnitPrice());
                // 增加时段价格
                tbBizPlaceBuyContractDetail.setTimePrice(placeBuyContractDetail.getTimePrice());

                tbBizPlaceBuyContractDetail.setPlaceUnitExpires(placeBuyContractDetail.getPlaceUnitExpires());
                tbBizPlaceBuyContractDetail.setExpiresUnit("小时");

                tbBizPlaceBuyContractDetail.setBuyStartTime(DateUtils.strToDate("2016-01-01 "+placeBuyContractDetail.getBuyStartTime(),DateUtils.DATE_FORMAT_YYYY_MM_DD_HH_MM_SS));
                tbBizPlaceBuyContractDetail.setBuyEndTime(DateUtils.strToDate("2016-01-01 " +placeBuyContractDetail.getBuyEndTime(),DateUtils.DATE_FORMAT_YYYY_MM_DD_HH_MM_SS));
                tbBizPlaceBuyContractDetail.setDateRange(placeBuyContractDetail.getDateRange());
                tbBizPlaceBuyContractDetail.setAttractId(tbBizPlaceBuyContract.getId());
                tbBizPlaceBuyContractDetail.setBuyType(placeBuyContract.getBuyType());
                tbBizPlaceBuyContractDetail.setPlaceUnitId(placeBuyContractDetail.getPlaceUnitId());
                tbBizPlaceBuyContractDetail.setUid(adminUser.getId());
                tbBizPlaceBuyContractDetail.setDeptId(adminUser.getDeptId());

                placeBuyContractDetailMapper.insertSelective(tbBizPlaceBuyContractDetail);
                flag ++ ;
                this.updatePlaceUnitSign(placeBuyContractDetail.getPlaceUnitId());
            }
        }
        return flag;
    }

    /**
     * 更新场馆签约状态
     * @param placeId
     * @return
     */
    public int updatePlaceSign(Integer placeId){
        TbBizPlace place = new TbBizPlace();
        place.setIsSign((byte)1);
        place.setId(placeId);
        int flag = placeMapper.updateByPrimaryKeySelective(place);
        return flag;
    }

    /**
     * 更新场馆场地签约状态
     * @param placeUnitId
     * @return
     */
    public int updatePlaceUnitSign(Integer placeUnitId){
        TbBizPlaceUnit placeUnit = new TbBizPlaceUnit();
        placeUnit.setIsSign((byte) 1);
        placeUnit.setId(placeUnitId);
        int flag = placeUnitMapper.updateByPrimaryKeySelective(placeUnit);
        return flag;
    }

    /**
     * 获取场馆附加信息
     * @param placeId
     * @return
     */
    public TbBizPlaceAttach getPlaceAttachInfo(Integer placeId){

        TbBizPlaceAttachExample example = new TbBizPlaceAttachExample();
        example.createCriteria().andPlaceIdEqualTo(placeId);
        List<TbBizPlaceAttach> list = placeAttachMapper.selectByExample(example);
        if (list.isEmpty()) {
            return null;
        }else{
            return list.get(0);
        }
    }

     public static PlaceBuyContractDetail newPlaceBuyContractDetailFromTbDetail(TbBizPlaceBuyContractDetail tbBizPlaceBuyContractDetail) {
        PlaceBuyContractDetail placeBuyContractDetail = new PlaceBuyContractDetail();
        placeBuyContractDetail.setPlaceUnitId(tbBizPlaceBuyContractDetail.getPlaceUnitId());
        placeBuyContractDetail.setAttractId(tbBizPlaceBuyContractDetail.getAttractId());
        placeBuyContractDetail.setExpiresUnit(tbBizPlaceBuyContractDetail.getExpiresUnit());
        placeBuyContractDetail.setId(tbBizPlaceBuyContractDetail.getId());
        placeBuyContractDetail.setPlaceId(tbBizPlaceBuyContractDetail.getPlaceId());
        placeBuyContractDetail.setFinishDate(tbBizPlaceBuyContractDetail.getFinishDate());
        placeBuyContractDetail.setPlaceUnitPrice(tbBizPlaceBuyContractDetail.getPlaceUnitPrice());
        placeBuyContractDetail.setBuyType(tbBizPlaceBuyContractDetail.getBuyType());

        placeBuyContractDetail.setTimePrice(tbBizPlaceBuyContractDetail.getTimePrice());

        //整馆买入或者包片买入
        if(tbBizPlaceBuyContractDetail.getBuyType().equals(1) || tbBizPlaceBuyContractDetail.getBuyType().equals(2)){
            placeBuyContractDetail.setPlaceUnitExpires(tbBizPlaceBuyContractDetail.getPlaceUnitExpires());
        }
        //时段买入,真包时,假包时
        if(tbBizPlaceBuyContractDetail.getBuyType().equals(3) ||
                tbBizPlaceBuyContractDetail.getBuyType().equals(4) ||
                tbBizPlaceBuyContractDetail.getBuyType().equals(5)) {
            placeBuyContractDetail.setBuyStartTime(DateUtils.DateToTime(tbBizPlaceBuyContractDetail.getBuyStartTime()));
            placeBuyContractDetail.setBuyEndTime(DateUtils.DateToTime(tbBizPlaceBuyContractDetail.getBuyEndTime()));
            placeBuyContractDetail.setDateRange(tbBizPlaceBuyContractDetail.getDateRange());
        }

        return placeBuyContractDetail;
    }

    /**
     * 通过场馆场地ID获取合同详情列表
     * @param placeUnitId
     * @return
     */
    public List<PlaceBuyContractDetail> getPlaceBuyContractDetailByPlaceUnitId(Integer placeUnitId,Integer attractId){
        TbBizPlaceBuyContractDetailExample example = new TbBizPlaceBuyContractDetailExample();

        example.createCriteria().andPlaceUnitIdEqualTo(placeUnitId).andAttractIdEqualTo(attractId);
        List<TbBizPlaceBuyContractDetail> tbBizPlaceBuyContractDetailList = placeBuyContractDetailMapper.selectByExample(example);
        List<PlaceBuyContractDetail> list = new ArrayList<>();
        PlaceBuyContractDetail placeBuyContractDetail ;
        for (TbBizPlaceBuyContractDetail tbBizPlaceBuyContractDetail : tbBizPlaceBuyContractDetailList) {
            /*
            placeBuyContractDetail = new PlaceBuyContractDetail();
            placeBuyContractDetail.setPlaceUnitId(tbBizPlaceBuyContractDetail.getPlaceUnitId());
            placeBuyContractDetail.setAttractId(tbBizPlaceBuyContractDetail.getAttractId());
            placeBuyContractDetail.setExpiresUnit(tbBizPlaceBuyContractDetail.getExpiresUnit());
            placeBuyContractDetail.setId(tbBizPlaceBuyContractDetail.getId());
            placeBuyContractDetail.setPlaceId(tbBizPlaceBuyContractDetail.getPlaceId());
            placeBuyContractDetail.setFinishDate(tbBizPlaceBuyContractDetail.getFinishDate());
            placeBuyContractDetail.setPlaceUnitPrice(tbBizPlaceBuyContractDetail.getPlaceUnitPrice());
            placeBuyContractDetail.setBuyType(tbBizPlaceBuyContractDetail.getBuyType());

            placeBuyContractDetail.setTimePrice(tbBizPlaceBuyContractDetail.getTimePrice());

            //整馆买入或者包片买入
            if(tbBizPlaceBuyContractDetail.getBuyType().equals(1) || tbBizPlaceBuyContractDetail.getBuyType().equals(2)){
                placeBuyContractDetail.setPlaceUnitExpires(tbBizPlaceBuyContractDetail.getPlaceUnitExpires());
            }
            //时段买入,真包时,假包时
            if(tbBizPlaceBuyContractDetail.getBuyType().equals(3) ||
                    tbBizPlaceBuyContractDetail.getBuyType().equals(4) ||
                    tbBizPlaceBuyContractDetail.getBuyType().equals(5)) {
                placeBuyContractDetail.setBuyStartTime(DateUtils.DateToTime(tbBizPlaceBuyContractDetail.getBuyStartTime()));
                placeBuyContractDetail.setBuyEndTime(DateUtils.DateToTime(tbBizPlaceBuyContractDetail.getBuyEndTime()));
                placeBuyContractDetail.setDateRange(tbBizPlaceBuyContractDetail.getDateRange());
            }*/
            placeBuyContractDetail = newPlaceBuyContractDetailFromTbDetail(tbBizPlaceBuyContractDetail);
            list.add(placeBuyContractDetail);
        }
        return list;
    }

    /**
     * 通过场馆ID获取合同基本信息
     * @param placeId
     * @return
     */
    public List<TbBizPlaceBuyContract> getPlaceBuyContractByPlaceId(Integer placeId){
        TbBizPlaceBuyContractExample example = new TbBizPlaceBuyContractExample();
        example.createCriteria().andPlaceIdEqualTo(placeId).andIsDeleteEqualTo((byte)0);

        List<TbBizPlaceBuyContract> list = placeBuyContractMapper.selectByExample(example);

        return list;
    }

    /**
     * 通过场馆场地ID获取场地合同详情列表
     * @param placeUnitId
     * @return
     */
    public List<TbBizPlaceBuyContractDetail> getPlaceBuyContractDetail(Integer placeUnitId){
        TbBizPlaceBuyContractDetailExample example = new TbBizPlaceBuyContractDetailExample();
        TbBizPlaceBuyContractDetailExample.Criteria criteria = example.createCriteria();
        criteria.andPlaceUnitIdEqualTo(placeUnitId);
        criteria.andIsDeleteEqualTo((byte)0);
        criteria.andIsExpireEqualTo((byte)0);
        List<TbBizPlaceBuyContractDetail> list = placeBuyContractDetailMapper.selectByExample(example);
        return list;
    }

    /**
     * 通过场馆ID获取场地列表
     * @param placeId
     * @return
     */
    private List<TbBizPlaceUnit> getPlaceUnitList(Integer placeId){
        TbBizPlaceUnitExample example = new TbBizPlaceUnitExample();
        example.createCriteria().andPlaceIdEqualTo(placeId);
        List<TbBizPlaceUnit> list = placeUnitMapper.selectByExample(example);
        return list;
    }

    /**
     * 通过场馆场地ID获取场地营业时间列表
     * @param placeUnitId
     * @return
     */
    private List<TbBizPlaceUnitTime> getPlaceUnitPrimeTimeList(Integer placeUnitId){
        TbBizPlaceUnitTimeExample example = new TbBizPlaceUnitTimeExample();
        example.createCriteria().andPlaceUnitIdEqualTo(placeUnitId);
        List<TbBizPlaceUnitTime> list = placeUnitTimeMapper.selectByExample(example);
        return list;
    }

    /**
     * 通过合同ID获取合同详情列表
     * @param attractId
     * @return
     */
    private List<TbBizPlaceBuyContractDetail> getPlaceBuyContractDetailListByContractId(Integer attractId){
        TbBizPlaceBuyContractDetailExample example = new TbBizPlaceBuyContractDetailExample();
        example.createCriteria().andAttractIdEqualTo(attractId);
        List<TbBizPlaceBuyContractDetail> list = placeBuyContractDetailMapper.selectByExample(example);
        return list;
    }

    /**
     * 购买年限超过上限
     * @param placeBuyContract
     * @return
     */
    private boolean isBuyOvertopMax(PlaceBuyContract placeBuyContract){
        Date start = placeBuyContract.getBuyDate();
        int buyType = placeBuyContract.getBuyType();
        List<PlaceBuyContractDetail> placeBuyContractDetailList = placeBuyContract.getPlaceBuyContractDetails();
        if (!placeBuyContractDetailList.isEmpty()) {
            for (PlaceBuyContractDetail placeBuyContractDetail : placeBuyContractDetailList) {
                if(buyType == 3){
                    Date end = placeBuyContractDetail.getFinishDate();
                    double year = DateTimeUtils.diffDays(start,end)/365.0;
                    //购买年限不要超过四年
                    return year > 5;
                }
                if(buyType == 1 || buyType == 2){
                    double year = placeBuyContractDetail.getPlaceUnitExpires();
                    //购买年限不要超过四年
                    if(year > 5){
                        return true;
                    }else{
                        continue;
                    }
                }
            }
        }
        return false;
    }

    /**
     * 更新合同过期状态（0为未过期，1为过期）
     * @param placeBuyContractDetailId 合同详情ID
     * @return 是否过期
     */
    private boolean updatePlaceBuyContractDetailExpire(int placeBuyContractDetailId){
        TbBizPlaceBuyContractDetailExample example = new TbBizPlaceBuyContractDetailExample();
        TbBizPlaceBuyContractDetailExample.Criteria criteria = example.createCriteria();
        criteria.andIdEqualTo(placeBuyContractDetailId);

        TbBizPlaceBuyContractDetail record = new TbBizPlaceBuyContractDetail();
        record.setIsExpire((byte)1);

        int n = placeBuyContractDetailMapper.updateByExampleSelective(record,example);
        return n > 0;
    }

}
